import asyncio
import json
from tortoise import Tortoise, fields, run_async
from models.models import Post, PostDteta  # 确保这些模型已经定义
TORTOISE_ORM = {
    "connections": {
        "default": {
            "engine": "tortoise.backends.mysql",  # 数据库引擎 Mysql or Mariadb
            "credentials": {
                "host": "127.0.0.1",  # 地址
                "port": "3306",  # 端口
                "user": "root",  # 用户名
                "password": "gx20020225",  # 密码
                "database": "blog",  # 数据库名称（需要提前创建数据库）
                "minsize": 1,  # 最少连接
                "maxsize": 5,  # 最大连接
                "echo": True  # 是否反馈SQL语句
            }
        }
    },
    "apps": {
        "models": {
            "models": ["models.models","aerich.models"],  # models数据模型迁移
            "default_connection": "default"
        }
    },
    "use_tz": False,
    "timezone": "Asia/Shanghai"
}
# 读取 JSON 文件
with open('posts.json', 'r', encoding='utf8') as file:
    data = json.load(file)

async def write_to_database(data):
    for item in data:
        if not item['imageSrc']:
            continue
        # 检查是否已经存在记录
        if await PostDteta.exists(id=item['id']):
            print(f"记录 {item['id']} 已存在，跳过...")
            continue

        if await Post.exists(id=item['id']):
            print(f"记录 {item['id']} 已存在，跳过...")
            continue

        # 插入 PostDteta
        post_detail = await PostDteta.create(
            id=item['id'],
            imageSrc=item['imageSrc'],
            Collection=item['Collection'],
            payType=item['payType'],
            level_limit=item['level_limit'],
            level=item['level'],
            data_id=item['nid_post']
        )

        author_id = item['author_id']
        tags_id = item['tags_id']

        # 插入 Post
        await Post.create(
            id=item['id'],
            imageSrc=item['imageSrc'][0],
            text=item['text'],
            title=item['title'],
            isTop=item['isTop'],
            likes=item['likes'],
            comments_count=item['comments_count'],
            views=item['views'],
            publishDate=item['publishDate'],
            author_id=author_id,
            tags_id=tags_id,
            is_show=item['is_show'],
            is_slider=item['is_slider'],
            post_detail_id=post_detail.id
        )

async def main():
    # 连接到数据库
    await Tortoise.init(config=TORTOISE_ORM)
    await Tortoise.generate_schemas()

    # 写入数据到数据库
    await write_to_database(data)

    # 关闭数据库连接
    await Tortoise.close_connections()

# 运行异步 main 函数
run_async(main())


# 配置数据库连接

